//
//  AnswerScrollView.m
//  DriveStudy
//
//  Created by chen on 2017/4/14.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "AnswerScrollView.h"

#define SIZE self.frame.size
#define CellIdentifier @"AnswerTableViewCell"

@interface AnswerScrollView()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>{
    UITableView * _leftTableView;
    UITableView * _mainTableView;
    UITableView * _rightTableView;
    
    
}
@end

@implementation AnswerScrollView

-(instancetype)initWithFrame:(CGRect)frame withDataArray:(NSArray *)array andCurrentPage:(int)page{
    self = [super initWithFrame:frame];
    if (self) {
        _dataArray = [[NSArray alloc]initWithArray:array];
        _hasAnswerArray = [[NSMutableArray alloc]init];
        //存储所有答过题目的题目编号
        //没有答过的设为0,答过题的设置成答案数据
        for (int i =0 ; i < _dataArray.count -1 ; i++) {
            [_hasAnswerArray addObject:@"0"];
        }
        
        _scrollview = [[UIScrollView alloc]initWithFrame:frame];
        _scrollview.delegate = self;
        //翻页效果
        _scrollview.pagingEnabled = YES;
        //回弹的动态效果
        _scrollview.bounces = NO;
        //水平方向上的标尺效果
        _scrollview.showsHorizontalScrollIndicator = NO;
        _scrollview.showsVerticalScrollIndicator = NO;
        //赋值当前的页面值
//        _currentPage = page;
        //判断当前的页面数量
        if (_dataArray.count > 1) {
            _scrollview.contentSize = CGSizeMake(SIZE.width * 2, 0);
        }
        _leftTableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _mainTableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _rightTableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        [self createView];
    }
    return self;
    
}
-(void)createView{
    _leftTableView.frame = CGRectMake(0, 0, SIZE.width, SIZE.height);
    _mainTableView.frame = CGRectMake(SIZE.width, 0, SIZE.width, SIZE.height);
    _rightTableView.frame = CGRectMake(SIZE.width * 2, 0, SIZE.width, SIZE.height);
    [_scrollview addSubview:_leftTableView];
    [_scrollview addSubview:_mainTableView];
    [_scrollview addSubview:_rightTableView];
    [self addSubview:_scrollview];
}

#pragma mark - tableView协议实现方式

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    AnswerModel *answerModel = [self getModel:tableView];
    if ([answerModel.mtype intValue] == 1) {
        return 4;
    }else{
        return 2;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
   
    AnswerModel *answerModel = [self getModel:tableView];
    CGFloat height;
    if ([answerModel.mtype intValue] == 1) {
        NSString *str = [[Tool getAnswerFromString:answerModel.mquestion]objectAtIndex:0];
        UIFont *font = [UIFont systemFontOfSize:16];
        height = [Tool getSizeFromString:str withFont:font withSize:CGSizeMake(tableView.frame.size.width - 20, 400)].height +20;
    }else{
        NSString *str = answerModel.mquestion;
        UIFont *font = [UIFont systemFontOfSize:16];
        height = [Tool getSizeFromString:str withFont:font withSize:CGSizeMake(tableView.frame.size.width - 20, 400)].height +20;
    }
    if (height < 150 ) {
        height = 150;
    }
    return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    AnswerModel *answerModel = [self getModel:tableView];
    NSString *str = [NSString stringWithFormat:@"答案解析:%@",answerModel.mdesc];
    UIFont *font = [UIFont systemFontOfSize:16];
    CGFloat height = [Tool getSizeFromString:str withFont:font withSize:CGSizeMake(tableView.frame.size.width - 20, 400)].height +20;
    return  height;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    AnswerModel *answerModel = [self getModel:tableView];
    
    NSString *str = [NSString stringWithFormat:@"答案解析:%@",answerModel.mdesc];
    UIFont *font = [UIFont systemFontOfSize:16];
    CGFloat height = [Tool getSizeFromString:str withFont:font withSize:CGSizeMake(tableView.frame.size.width - 20, 400)].height +20;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SIZE.width, height)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, tableView.frame.size.width - 20, height - 20)];
    label.text = str;
    label.font = [UIFont systemFontOfSize:16];
    label.numberOfLines = 0;
    label.textColor = [UIColor greenColor];
    [view addSubview:label];
    if ([[_hasAnswerArray objectAtIndex:_currentPage] intValue] != 0) {
        return view;
    }
    return nil;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    AnswerModel *answerModel = [self getModel:tableView];
    CGFloat height;
    NSString *str;
    if ([answerModel.mtype intValue] == 1) {
        str = [[Tool getAnswerFromString:answerModel.mquestion]objectAtIndex:0];
        UIFont *font = [UIFont systemFontOfSize:16];
        height = [Tool getSizeFromString:str withFont:font withSize:CGSizeMake(tableView.frame.size.width - 20, 400)].height +20;
    }else{
        str = answerModel.mquestion;
        UIFont *font = [UIFont systemFontOfSize:16];
        height = [Tool getSizeFromString:str withFont:font withSize:CGSizeMake(tableView.frame.size.width - 20, 400)].height +20;
    }
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SIZE.width, height)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, tableView.frame.size.width - 20, height - 20)];
    label.text = [NSString stringWithFormat:@"%d.%@",[self getQuestionNumber:tableView andCurrentPage:_currentPage],str];
    label.font = [UIFont systemFontOfSize:16];
    label.numberOfLines = 0;
    [view addSubview:label];
    if (answerModel.mimage != nil) {
        UIImageView *imageView= [[UIImageView alloc]initWithFrame:CGRectMake(SIZE.width/2 - 50, height +2, 66, 66)];
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",answerModel.mid]];
        [view addSubview:imageView];
    }
    return view;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AnswerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:CellIdentifier owner:self options:nil]lastObject];
        cell.numberLabel.layer.masksToBounds = YES;
        cell.numberLabel.layer.cornerRadius = 10;
        cell.numberImage.layer.masksToBounds = YES;
        cell.numberImage.layer.cornerRadius = 10;
        NSInteger count = indexPath.row;
        //0是假，0以外都是真
        if (count%2) {
            cell.backgroundColor = [UIColor lightGrayColor];
        }
        //去除选中效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.numberLabel.text = [NSString stringWithFormat:@"%c",(char)('A'+indexPath.row)];
    //这种数据模型没有想明白，需要认真思考一下这个模型情况
    AnswerModel *answerModel = [self getModel:tableView];
    int page = [self getQuestionNumber:tableView andCurrentPage:_currentPage];
    //选择错误那么需要显示答案
    if ([answerModel.mtype intValue] == 1) {
        cell.answerLabel.text = [[Tool getAnswerFromString:answerModel.mquestion] objectAtIndex:indexPath.row + 1];
        if ([[_hasAnswerArray objectAtIndex:page -1] intValue] != 0) {
            //把选择项与答案项进行比较
            //判断当前的答案正确与否
            if ([answerModel.manswer isEqualToString:[NSString stringWithFormat:@"%c",(char)('A'+indexPath.row)]]) {
                [cell.numberLabel setHidden:YES];
                [cell.numberImage setHidden:NO];
                [cell.numberImage setImage:[UIImage imageNamed:@"19.png"]];
                //            [self showAlertMessage:@"回答正确"];
            }else if (![answerModel.manswer isEqualToString:[NSString stringWithFormat:@"%c",(char)('A'+indexPath.row)]] && indexPath.row == [_hasAnswerArray[page - 1] intValue] - 1){
                [cell.numberImage setImage:[UIImage imageNamed:@"20.png"]];
                [cell.numberLabel setHidden:YES];
                [cell.numberImage setHidden:NO];
                
            }else{
                [cell.numberLabel setHidden:NO];
                [cell.numberImage setHidden:YES];
            }
            
        }else{
            [cell.numberLabel setHidden:NO];
            [cell.numberImage setHidden:YES];
        }
        return cell;
    }else{
        cell.answerLabel.text = indexPath.row ? @"对":@"错";
        if ([[_hasAnswerArray objectAtIndex:page -1] intValue] != 0) {
            //把选择项与答案项进行比较
            NSString *answer = _hasAnswerArray[page - 1] ? @"对":@"错";
            //判断当前的答案正确与否
            if ([answerModel.manswer isEqualToString:answer]) {
                [cell.numberLabel setHidden:YES];
                [cell.numberImage setHidden:NO];
                [cell.numberImage setImage:[UIImage imageNamed:@"19.png"]];
                //            [self showAlertMessage:@"回答正确"];
            }else if (![answerModel.manswer isEqualToString:answer] && indexPath.row == [_hasAnswerArray[page - 1] intValue] - 1){
                [cell.numberImage setImage:[UIImage imageNamed:@"20.png"]];
                [cell.numberLabel setHidden:YES];
                [cell.numberImage setHidden:NO];
                
            }else{
                [cell.numberLabel setHidden:NO];
                [cell.numberImage setHidden:YES];
            }
            
        }else{
            [cell.numberLabel setHidden:NO];
            [cell.numberImage setHidden:YES];
        }
        return cell;
    }
}
-(int)getQuestionNumber:(UITableView *)tableView andCurrentPage:(int)page{
    if (tableView == _leftTableView && page == 0) {
        return 1;
    }else if (tableView == _leftTableView && page > 0){
        return page;
    }else if (tableView == _mainTableView && page == 0){
        return 2;
    }else if (tableView == _mainTableView && page > 0 && page < _dataArray.count -1){
        return page +1;
    }else if (tableView == _mainTableView && page == _dataArray.count - 1){
        return page;
    }else if (tableView == _rightTableView && page  == _dataArray.count -1){
        return page + 2;
    }else if (tableView == _rightTableView && page < _dataArray.count -1){
        return page + 1;
    }
    return 0;
}
-(AnswerModel *)getModel:(UITableView *)tableView{
    AnswerModel *answerModel;
    if (tableView == _leftTableView && _currentPage == 0) {
        answerModel = _dataArray[_currentPage];
    }else if (tableView == _leftTableView && _currentPage > 0){
        answerModel = _dataArray[_currentPage - 1];
    }else if (tableView == _mainTableView && _currentPage == 0){
        answerModel = _dataArray[_currentPage + 1];
    }else if (tableView == _mainTableView && _currentPage > 0 && _currentPage < _dataArray.count -1){
        answerModel = _dataArray[_currentPage];
    }else if (tableView == _mainTableView && _currentPage == _dataArray.count - 1){
        answerModel = _dataArray[_currentPage + 1];
    }else if (tableView == _rightTableView && _currentPage  == _dataArray.count -1){
        answerModel = _dataArray[_currentPage];
    }else if (tableView == _rightTableView && _currentPage < _dataArray.count -1){
        answerModel = _dataArray[_currentPage +1];
    }
    return answerModel;
}
//弹出提示答题正确的提示窗口，好像在uiview视图中不能使用presentViewController方法，这是uiviewcontroller特有的
-(void)showAlertMessage:(NSString *)message{
    UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 225, 120, 30)];
    // 设置提示内容
    [tipLabel setText:message];
    tipLabel.backgroundColor = [UIColor blackColor];
    tipLabel.layer.cornerRadius = 5;
    tipLabel.layer.masksToBounds = YES;
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor whiteColor];
    [self addSubview:tipLabel];
    // 设置时间和动画效果
    [UIView animateWithDuration:2.0 animations:^{
        tipLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        // 动画完毕从父视图移除
        [tipLabel removeFromSuperview];
    }];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[_hasAnswerArray objectAtIndex:_currentPage] intValue] != 0) {
        return;
    }else{
        [_hasAnswerArray replaceObjectAtIndex:_currentPage withObject:[NSString stringWithFormat:@"%ld",indexPath.row + 1]];
    }
    //添加错误的题目到磁盘上去
    AnswerModel *answerModel = [self getModel:tableView];
    int page = [self getQuestionNumber:tableView andCurrentPage:_currentPage];
    NSString *answer = _hasAnswerArray[page - 1] ? @"对":@"错";
    if ([answerModel.mtype intValue] == 1){
        if (![answerModel.manswer isEqualToString:[NSString stringWithFormat:@"%c",(char)('A'+indexPath.row)]]) {
            [UserDefaultManager addWrongQuestion:answerModel.mid];
        }
    }else{
        if (![answerModel.manswer isEqualToString:answer]) {
            [UserDefaultManager addWrongQuestion:answerModel.mid];
        }
    }
    
    //重新加载tableView数据
    [self reloadData];
}


#pragma mark - scrollView协议实现方式

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGPoint currentOffset = scrollView.contentOffset;
    int page = currentOffset.x / SIZE.width;
    if (page > 0 && page < _dataArray.count - 1 ) {
        _scrollview.contentSize = CGSizeMake(currentOffset.x + SIZE.width * 2, 0);
        _leftTableView.frame = CGRectMake(currentOffset.x - SIZE.width, 0, SIZE.width, SIZE.height);
        _mainTableView.frame = CGRectMake(currentOffset.x, 0, SIZE.width, SIZE.height);
        _rightTableView.frame = CGRectMake(currentOffset.x + SIZE.width, 0, SIZE.width, SIZE.height);
    }else{
        _scrollview.contentSize = CGSizeMake(currentOffset.x + SIZE.width * 2, 0);
        _leftTableView.frame = CGRectMake(currentOffset.x , 0, SIZE.width, SIZE.height);
        _mainTableView.frame = CGRectMake(currentOffset.x + SIZE.width, 0, SIZE.width, SIZE.height);
        _rightTableView.frame = CGRectMake(currentOffset.x + SIZE.width*2, 0, SIZE.width, SIZE.height);
    }
    _currentPage = page;
    [self reloadData];
}
-(void)reloadData{
    [_leftTableView reloadData];
    [_mainTableView reloadData];
    [_rightTableView reloadData];
}

@end
